package com.gjp.controller;

import com.gjp.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * Created by gjp on 2017-6-6.
 */
@RestController
public class LoginController {

    //返回页面
    private String loginViewName="/login/login";    //登录页面
    private String indexViewName="/login/index";    //首页
    private String viewName403="/login/403";    //未授权页面


    /**
     * 登录页面
     * @return
     */
    @GetMapping("/login")
    public ModelAndView login(){
        ModelAndView modelAndView = new ModelAndView(loginViewName);
        //如果用户登录过了，就跳转到首页
        if (SecurityUtils.getSubject().isAuthenticated()){
            modelAndView.setViewName(indexViewName);
        }
        return modelAndView;
    }

    /**
     * 登录认证
     * @return
     */
    @PostMapping("/doLogin")
    public ModelAndView ajaxLogin(User user, boolean rememberMe){
        ModelAndView modelAndView = new ModelAndView(indexViewName);
        try {
            //将用户名和密码传入token调用登录方法
            UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword(),rememberMe);
            SecurityUtils.getSubject().login(token);
        }catch (Exception e){
            modelAndView.setViewName(loginViewName);
            modelAndView.addObject("error",e.getMessage());
        }
        return modelAndView;
    }

    @GetMapping("/logout")
    public ModelAndView logout(){
        ModelAndView modelAndView = new ModelAndView(loginViewName);
        try {
            SecurityUtils.getSubject().logout();
        }catch (Exception e){
            modelAndView.addObject("error",e.getMessage());
        }
        return modelAndView;
    }

    /**
     * 登录成功
     * @return
     */
    @GetMapping("/index")
    public ModelAndView index(){
        ModelAndView modelAndView = new ModelAndView(indexViewName);
        return modelAndView;
    }

    /**
     * 未授权
     * @return
     */
    @GetMapping("/403")
    public ModelAndView error(){
        ModelAndView modelAndView = new ModelAndView(viewName403);
        return modelAndView;
    }
}
